package com.explore.demo.service.impl;

import com.aliyuncs.CommonResponse;
import com.aliyuncs.exceptions.ClientException;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.explore.demo.VO.RecruitmentSearchVO;
import com.explore.demo.VO.ResumeInfoVO;
import com.explore.demo.VO.UserInfoVO;
import com.explore.demo.cache.RedisCache;
import com.explore.demo.common.ResultCode;
import com.explore.demo.common.ServerResponse;
import com.explore.demo.config.JwtConfig;
import com.explore.demo.mapper.*;
import com.explore.demo.pojo.*;
import com.explore.demo.service.ResumeService;
import com.explore.demo.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.explore.demo.utils.ExploreUtils;
import com.explore.demo.utils.FileUtils;
import com.explore.demo.utils.MessageUtils;
import com.google.gson.internal.$Gson$Preconditions;
import org.jetbrains.annotations.NotNull;
import org.omg.CORBA.INTERNAL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gaolainan
 * @since 2021-04-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService
{

    /**
     * 打印日志文件
     */
    private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Value("${file.uploadUrl}")
    private String descPath;

    @Resource
    private MessageUtils messageUtils;

    @Resource
    private UserMapper userMapper;

    @Resource
    private JwtConfig jwtConfig;

    @Resource
    private RedisCache redisCache;

    @Resource
    private RecruitmentMapper recruitmentMapper;

    @Resource
    private CollectRelationMapper collectRelationMapper;

    @Resource
    private FileUtils fileUtils;

    @Resource
    private ResumeMapper resumeMapper;

    @Resource
    private DeliveryLogMapper deliveryLogMapper;

    @Resource
    private CompanyMapper companyMapper;

    @Override
    public ServerResponse register(String account, String password, HttpServletRequest request)
    {
        if (account == null)
        {
            return ServerResponse
                    .createBySuccessMessage(ResultCode.ACCOUNT_IS_NULL.getDescription(), ResultCode.ACCOUNT_IS_NULL.getCode(), null);
        }
        if (password == null)
        {
            return ServerResponse
                    .createBySuccessMessage(ResultCode.PASSWORD_IS_NULL.getDescription(), ResultCode.PASSWORD_IS_NULL.getCode(), null);
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        List<User> res = userMapper.selectList(wrapper);
        if (res.size() != 0)
        {
            return ServerResponse
                    .createBySuccessMessage(ResultCode.USER_ALREADY_EXISTS.getDescription(), ResultCode.USER_ALREADY_EXISTS.getCode(),
                                            null);
        }
        User user = new User();
        user.setAccount(account).setPassword(password).setHeadPortrait(descPath+"moren.jfif");
        return userMapper.insert(user) != 0 ? ServerResponse
                .createBySuccessMessage(ResultCode.SUCCESS.getDescription(), ResultCode.SUCCESS.getCode(), null) : ServerResponse
                       .createBySuccessMessage(ResultCode.USER_CREATE_FAIL.getDescription(), ResultCode.USER_CREATE_FAIL.getCode(), null);
    }

    @Override
    public ServerResponse login(@NotNull String account,@NotNull String password, HttpServletRequest request)
    {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        User user = userMapper.selectOne(wrapper);
        if (user == null){
            return ServerResponse.createBySuccessMessage("账号不存在", 2000, null);
        }
        logger.info("当前的登录对象的信息： =====> "+user.toString());
        if (!user.getPassword().equals(password))
        {
            return ServerResponse
                    .createBySuccessMessage(ResultCode.PASSWORD_IS_ERROR.getDescription(), ResultCode.PASSWORD_IS_ERROR.getCode(), null);
        }
        String token = jwtConfig.createToken(account);
        logger.info("成功生成token ====> "+token);
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setToken(token)
                  .setUser(user);
        return ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(), ResultCode.SUCCESS.getCode(), userInfoVO);
    }

    @Override
    public ServerResponse loginByVerifyCode(@NotNull String account,@NotNull String verifyCode, HttpServletRequest request){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        User user = userMapper.selectOne(wrapper);
        if (user == null){
            return ServerResponse.createBySuccessMessage("账号不存在", 2000, null);
        }
        if (redisCache.getCacheObject(account) == null)
        {
            return ServerResponse.createBySuccessMessage("发送的验证码已过期，请重新发送", 1000, null);
        }
        String code = redisCache.getCacheObject(account).toString();
        logger.info("缓存中的短信验证码 =====> "+code);

        logger.info("生成的验证码的内容： ===> " + code);
        if (!verifyCode.equals(code))
        {
            return ServerResponse.createBySuccessMessage("输入的验证码不正确", 1000, null);
        }
        String token = jwtConfig.createToken(account);
        logger.info("成功生成token ====> "+token);
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setToken(token)
                  .setUser(user);
        return ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(), ResultCode.SUCCESS.getCode(), userInfoVO);
    }

    @Override
    public ServerResponse logout(HttpServletRequest request)
    {
        return ExploreUtils.clearSession() ? ServerResponse
                .createBySuccessMessage(ResultCode.SUCCESS.getDescription(), ResultCode.SUCCESS.getCode(), null) : ServerResponse
                       .createBySuccessMessage(ResultCode.LOG_OUT_FAIL.getDescription(), ResultCode.LOG_OUT_FAIL.getCode(), null);
    }

    @Override
    public ServerResponse queryAllUsers(HttpServletRequest request)
    {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.ge("id", 1);
        List<User> list = userMapper.selectList(wrapper);
        return ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(), ResultCode.SUCCESS.getCode(), list);
    }

    @Override
    public ServerResponse queryUserByAccount(String account, HttpServletRequest request)
    {
        if (account == null)
        {
            return ServerResponse
                    .createBySuccessMessage(ResultCode.ACCOUNT_IS_NULL.getDescription(), ResultCode.ACCOUNT_IS_NULL.getCode(), null);
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        List<User> list = userMapper.selectList(wrapper);
        return list.size() == 0 ? ServerResponse
                .createBySuccessMessage(ResultCode.CHECK_NULL_INFO.getDescription(), ResultCode.CHECK_NULL_INFO.getCode(), null)
                                : ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(), ResultCode.SUCCESS.getCode(), list);
    }

    @Override
    public ServerResponse updateUser(User user, HttpServletRequest request)
    {
        if (user == null)
        {
            return ServerResponse.createBySuccessMessage(ResultCode.USER_IS_NULL.getDescription(), ResultCode.USER_IS_NULL.getCode(), null);
        }
        logger.info("jwt的header的内容是：===> "+jwtConfig.getHeader());
        /// return ServerResponse.createBySuccessMessage("用户身份已过期，需要重新登录");
        String token =  request.getHeader(jwtConfig.getHeader());
        String userName = jwtConfig.getUsernameFromToken(token);
        logger.info("当前登陆的用户为： ====> "+ userName);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account",userName);
        user.setId(userMapper.selectOne(wrapper).getId());
        return userMapper.updateById(user) != 0 ?
               ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(), ResultCode.SUCCESS.getCode(), null) :
               ServerResponse.createBySuccessMessage(ResultCode.UPDATE_ERROR.getDescription(), ResultCode.UPDATE_ERROR.getCode(), null);
    }

    @Override
    public ServerResponse deleteUser(String account, HttpServletRequest request)
    {
        if (account == null)
        {
            return ServerResponse
                    .createBySuccessMessage(ResultCode.ACCOUNT_IS_NULL.getDescription(), ResultCode.ACCOUNT_IS_NULL.getCode(), null);
        }
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.
                           eq("account", account);
        User one = userMapper.selectOne(userWrapper);
        wrapper.set("deleted", 1);
        return userMapper.update(one, wrapper) != 0 ? ServerResponse
                .createBySuccessMessage(ResultCode.SUCCESS.getDescription(), ResultCode.SUCCESS.getCode(), null) : ServerResponse
                       .createBySuccessMessage(ResultCode.UPDATE_FAIL.getDescription(), ResultCode.UPDATE_FAIL.getCode(), null);
    }

    @Override
    public ServerResponse generateVerifyCode(String account, HttpServletRequest request)
    {
        if (account == null)
        {
            return ServerResponse
                    .createBySuccessMessage(ResultCode.ACCOUNT_IS_NULL.getDescription(), ResultCode.ACCOUNT_IS_NULL.getCode(), null);
        }
        // 随机验证码
        String code = UUID.randomUUID().toString().substring(0, 4);
        logger.info("生成验证码的内容 ===> " + code);
        return messageUtils.getMessageRequest(account, code) ? ServerResponse.createBySuccessMessage("验证码发送成功", 200, null)
                                                             : ServerResponse.createBySuccessMessage("验证码发送失败", 1000, null);
    }

    @Override
    public ServerResponse getStarRecruitment(HttpServletRequest request)
    {
        String token = request.getHeader(jwtConfig.getHeader());
        String account = jwtConfig.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("account", account));
        List<Recruitment> nowUserStar = recruitmentMapper.getNowUserStar(account);
        List<RecruitmentSearchVO> list = new ArrayList<>();
        for (Recruitment tmp : nowUserStar){
            RecruitmentSearchVO searchVO = new RecruitmentSearchVO();
            QueryWrapper<Company> companyQueryWrapper = new QueryWrapper<>();
            companyQueryWrapper.eq("id", tmp.getCompanyId());
            Company one = companyMapper.selectOne(companyQueryWrapper);
            CollectRelation collectRelation = collectRelationMapper
                    .selectOne(new QueryWrapper<CollectRelation>().eq("recruit_id", tmp.getId()).eq("user_id", user.getId()));
            searchVO.setRecruitmentId(tmp.getId())
                    .setTitle(tmp.getTitle())
                    .setWorkPlace(tmp.getWorkCity())
                    .setCreateDate(tmp.getCreateTime())
                    .setExperience(tmp.getExperience())
                    .setSalaryUp(tmp.getSalaryUp())
                    .setSalaryDown(tmp.getSalaryDown())
                    .setEducation(tmp.getEducation())
                    .setNeedNum(tmp.getNeedNum())
                    .setRecruitCategory(recruitmentMapper.getAllCategory(tmp.getId()))
                    .setCompanyName(one.getCompanyName())
                    .setCollectDate(collectRelation.getCreateTime())
                    .setCompanyStatus(one.getStatus())
                    .setCompanyLogo(one.getCompanyLogo())
                    .setWelfareCategory(recruitmentMapper.getAllWelfareCategory(tmp.getId()))
                    .setCompanyCategory(companyMapper.getCategoryName(one.getId()));
            list.add(searchVO);
        }
        return ServerResponse.createBySuccessMessage("success", 200, list);
    }

    @Override
    public ServerResponse setStarRecruitment(HttpServletRequest request, Integer recruitmentId)
    {
        String token = request.getHeader(jwtConfig.getHeader());
        String account = jwtConfig.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("account", account));
        int res = collectRelationMapper.insert(new CollectRelation().setRecruitId(recruitmentId).setUserId(user.getId()));
        return res == 0?
               ServerResponse.createBySuccessMessage("error", 2000, null):
               ServerResponse.createBySuccessMessage("success", 200, null);
    }

    @Override
    public ServerResponse changeHeadPortrait(MultipartFile file, HttpServletRequest request)
    {
        String path = fileUtils.saveFile(file);
        String token = request.getHeader(jwtConfig.getHeader());
        String account = jwtConfig.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("account", account));
        logger.info("当前更换头像的用户为： ======> "+user.getVersion());
        user.setHeadPortrait(path);
        int res = userMapper.updateById(user);
        return res == 0?
               ServerResponse.createBySuccessMessage("修改失败", 2000, null):
               ServerResponse.createBySuccessMessage("上传成功", 200, null);
    }

    @Override
    public ServerResponse createResume(@NotNull String awardInfo,@NotNull String internship,@NotNull String personSummary, HttpServletRequest request)
    {
        String token = request.getHeader(jwtConfig.getHeader());
        String account = jwtConfig.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("account", account));
        Resume resume = new Resume();
        resume.setAwardInfo(awardInfo)
              .setInternship(internship)
              .setPersonalSummary(personSummary)
              .setUserId(user.getId());
        int res = resumeMapper.insert(resume);
        return res == 0?
               ServerResponse.createBySuccessMessage("error", 2000, null):
               ServerResponse.createBySuccessMessage("success", 200, null);
    }

    @Override
    public ServerResponse showOwnResume(HttpServletRequest request)
    {
        String token = request.getHeader(jwtConfig.getHeader());
        String account = jwtConfig.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("account", account));
        QueryWrapper<Resume> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", user.getId());
        Resume resume = resumeMapper.selectOne(wrapper);
        ResumeInfoVO resumeInfoVO = new ResumeInfoVO();
        resumeInfoVO.setRealName(user.getRealName())
                    .setGender(user.getGender())
                    .setBirthDay(user.getBirthDay())
                    .setPhone(user.getPhone())
                    .setMail(user.getMail())
                    .setProvince(user.getProvince())
                    .setCity(user.getCity())
                    .setCollege(user.getCollege())
                    .setAdmissionDate(user.getAdmissionDate())
                    .setGraduateDate(user.getGraduateDate())
                    .setMajorProfession(user.getMajorProfession())
                    .setAwardInfo(resume.getAwardInfo())
                    .setInternship(resume.getInternship())
                    .setPersonalSummary(resume.getPersonalSummary());
        return ServerResponse.createBySuccessMessage("success", 200, resumeInfoVO);
    }

    @Override
    public ServerResponse showOwnDeliveryLog(HttpServletRequest request)
    {
        String token = request.getHeader(jwtConfig.getHeader());
        String account = jwtConfig.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("account", account));
        List<Recruitment> res = new ArrayList<>();
        List<DeliveryLog> logs = deliveryLogMapper.selectList(new QueryWrapper<DeliveryLog>().eq("user_id", user.getId()));
        for (DeliveryLog tmp : logs){
            res.add(recruitmentMapper.selectOne(new QueryWrapper<Recruitment>().eq("id", tmp.getRecruitId())));
        }
        List<RecruitmentSearchVO> list = new ArrayList<>();
        for (Recruitment tmp : res){
            RecruitmentSearchVO searchVO = new RecruitmentSearchVO();
            QueryWrapper<Company> companyQueryWrapper = new QueryWrapper<>();
            companyQueryWrapper.eq("id", tmp.getCompanyId());
            Company one = companyMapper.selectOne(companyQueryWrapper);
            searchVO.setRecruitmentId(tmp.getId())
                    .setTitle(tmp.getTitle())
                    .setWorkPlace(tmp.getWorkCity())
                    .setCreateDate(tmp.getCreateTime())
                    .setExperience(tmp.getExperience())
                    .setSalaryUp(tmp.getSalaryUp())
                    .setSalaryDown(tmp.getSalaryDown())
                    .setEducation(tmp.getEducation())
                    .setNeedNum(tmp.getNeedNum())
                    .setRecruitCategory(recruitmentMapper.getAllCategory(tmp.getId()))
                    .setCompanyName(one.getCompanyName())
                    .setCompanyStatus(one.getStatus())
                    .setCompanyLogo(one.getCompanyLogo())
                    .setWelfareCategory(recruitmentMapper.getAllWelfareCategory(tmp.getId()))
                    .setCompanyCategory(companyMapper.getCategoryName(one.getId()));
            list.add(searchVO);
        }
        return ServerResponse.createBySuccessMessage("success", 200, list);
    }


}
